﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using SCFHS.Data;

namespace SCFHS
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            {
                FormsAuthentication.SignOut();
                return;
            }
            if (cookie != null)
            {
                FormsAuthenticationTicket logTicket = FormsAuthentication.Decrypt(cookie.Value);
                System.Web.Security.FormsIdentity identity = new System.Web.Security.FormsIdentity(logTicket);
                if (string.IsNullOrEmpty(logTicket.UserData))
                    FormsAuthentication.SignOut();
                string[] userData = logTicket.UserData.Split('|');
                if (userData == null)
                    return;
                if (userData.Length < 6)
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect("~/Default.aspx");
                }
                User user = new User()
                {
                    userID = int.Parse(userData[0]),
                    userName = userData[1],
                    userProfileName = userData[2],
                    userDefaultPage = userData[3],
                    isActive=true,
                    isAdmin = Convert.ToBoolean(int.Parse(userData[4].ToString())),
                    userRole=userData[5]
                };

                this.Context.User = new User(identity, user);
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}